package com.yilijk.base.network.error;

import android.app.Activity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yilijk.base.BaseApi;
import com.yilijk.base.base.BaseDialog;
import com.yilijk.base.network.config.BaseRouter;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ActivityUtils;
import com.yilijk.base.utils.ToastUtils;

public class HttpErrorUtils {
    private static BaseDialog mTipsDialog;

    private HttpErrorUtils() {
    }

    public static void clearTipsDialog() {
        mTipsDialog = null;
    }

    private static void showAbnormalDialog(boolean login, String title, String tips) {
        Activity topActivity = ActivityUtils.getTopActivity();
        if (topActivity == null || topActivity.isFinishing()) {
            return;
        }

        if (mTipsDialog != null) {
            return;
        }

        BaseDialog.Builder builder = new BaseDialog.Builder(topActivity);
        builder.setTitle(title);
        builder.setMessage(tips);
        builder.setPositiveButton("确定", (dialog, which) -> {
            mTipsDialog = null;
            dialog.dismiss();
            if (login) {
                HttpUtils.cancelAll();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                BaseApi baseApi = (BaseApi) ARouter.getInstance().build(BaseRouter.Base).navigation();
                if (baseApi != null) {
                    baseApi.onCancelLogout(topActivity);
                }
                ActivityUtils.finishAllActivities();
            }
        });

        mTipsDialog = builder.create();
        mTipsDialog.setCancelable(false);
        try {
            mTipsDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void switchCode(int code) {
        Activity activity = ActivityUtils.getTopActivity();
        if (activity.isFinishing()) {
            return;
        }
        switch (code) {
            case 401:
                ToastUtils.showLong("系统异常，请重新登录");
                HttpUtils.cancelAll();
                Activity topActivity = ActivityUtils.getTopActivity();
                if (topActivity == null || topActivity.isFinishing()) {
                    return;
                }
                BaseApi baseApi = (BaseApi) ARouter.getInstance().build(BaseRouter.Base).navigation();
                if (baseApi != null) {
                    baseApi.onCancelLogout(topActivity);
                }
                break;
            case 406:
                showAbnormalDialog(true, "登录断开", "您的账号已在其他设备登录，请注意账号安全。");
                break;
            case 500:
                showAbnormalDialog(false, "网络错误", "哎呀！服务器开小差了，请稍后尝试。\n（ 错误代码:500 ）");
                break;
            default:
                break;
        }
    }
}
